<template>
  <div class="whole_black">
    <el-card class="box-card">
      <h3 slot="header" class="login-total">
        登录入口
        <el-tooltip class="item" effect="dark" content="手机号登录" placement="right">
          <router-link to="/loginPhone">
            <i class="el-icon-question"></i>
          </router-link>
        </el-tooltip>
      </h3>
      <div>
        <el-form
          v-loading="loading"
          :rules="userFormRules"
          ref="ruleForm"
          label-position="right"
          label-width="60px"
          :model="userForm"
        >
          <el-form-item label="学号" prop="cardNum">
            <el-input v-model="userForm.cardNum" placeholder="请输入学号" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" show-password>
            <el-input
              type="password"
              v-model="userForm.password"
              placeholder="请输入密码"
              clearable
              maxlength="16"
              show-word-limit
              @keyup.native.enter="submitForm('ruleForm')"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="userLogin" @click="submitForm('ruleForm')">登录</el-button>
            <el-button type="warning" @click="toRegister">注册</el-button>
          </el-form-item>
          <a @click="thirdToLogin()" class="imgLink" target="blank">
            <el-tooltip class="item" effect="dark" content="微信登录" placement="right">
              <img class="img-wechat" src="../../assets/wechat.jpg" alt />
            </el-tooltip>
          </a>
        </el-form>
      </div>
    </el-card>

    <el-dialog
      width="40%"
      :before-close="handleClose"
      :modal="false"
      title="忘记密码"
      :visible.sync="resetPwdDialog"
    >
      <el-form :rules="resetPwdrules" ref="resetForm" label-position="right" :model="resetPwd">
        <el-form-item prop="num" label-width="100px" label="验证方式：">
          <el-input clearable placeholder="请输入内容" v-model="resetPwd.num" class="input-with-select">
            <el-select class="resetPwd" v-model="resetPwd.type" slot="prepend" placeholder="请选择">
              <el-option label="手机号" value="1"></el-option>
              <el-option label="邮箱" value="2"></el-option>
            </el-select>
            <el-button @click="toSendCodeToMailOrPhone" slot="append" icon="el-icon-message"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" class="connect" label-width="100px" label="验证码：">
          <el-input clearable v-model="resetPwd.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="newPwd" class="connect" label-width="100px" label="新密码：">
          <el-input
            show-password
            type="password"
            clearable
            v-model="resetPwd.newPwd"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancalRestPwd">取 消</el-button>
        <el-button type="primary" @click="toResetPwd('resetForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Welcome",
  data() {
    var checkPwd = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
      let re = new RegExp(reg);
      if (!value) {
        return callback(new Error("密码不能为空"));
      } else if (!re.test(value)) {
        return callback(new Error("密码只能是数字与字母组合，且6-16位"));
      } else {
        callback();
      }
    };

    return {
      userForm: {
        cardNum: "",
        password: ""
      },
      userFormRules: {
        cardNum: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          { min: 9, max: 9, message: "学号是9位", trigger: "blur" }
        ],
        password: [{ validator: checkPwd, trigger: "blur" }]
      },
      loading: false,
      loginCount: 0,
      resetPwdDialog: false,
      resetPwd: {
        code: "",
        num: "",
        newPwd: "",
        type: "1"
      },
      resetPwdrules: {
        code: [{ required: true, message: "验证码", trigger: "blur" }],
        num: [
          { required: true, message: "联系方式不能为空", trigger: "change" }
        ],
        newPwd: [{ validator: checkPwd, trigger: "blur" }],
        type: [
          {
            required: true,
            message: "类型不能为空",
            trigger: "change"
          }
        ]
      }
    };
  },
  methods: {
    toSendCodeToMailOrPhone() {
      console.log(this.resetPwd.type);

      if (this.resetPwd.type == 2) {
        if (
          !/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(
            this.resetPwd.num
          )
        ) {
          return this.$message.warning("邮箱格式不对");
        }
      }
      if (this.resetPwd.type == 1)
        if (!/^1\d{10}$/.test(this.resetPwd.num)) {
          return this.$message.warning("手机号格式不对");
        }
      let params = new URLSearchParams();
      params.append("num", this.resetPwd.num);
      params.append("type", this.resetPwd.type);
      this.$http
        .put("user/noAuthorize/code", params)
        .then(resp => {
          let { code, msg } = resp.data;
          if (code == 1) {
            return this.$message.success(msg);
          } else {
            return this.$message.warning(msg);
          }
        })
        .catch(resp => {});
    },
    toResetPwd(resetForm) {
      this.$refs[resetForm].validate(valid => {
        if (valid) {
          let params = new URLSearchParams();
          params.append("code", this.resetPwd.code);
          params.append("num", this.resetPwd.num);
          params.append("newPwd", this.resetPwd.newPwd);
          this.$http
            .post("user/noAuthorize/reset_pwd", params)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code == 1) {
                this.resetPwdDialog = false;
                return this.$message.success(msg);
              } else {
                return this.$message.warning(msg);
              }
            })
            .catch(resp => {});
        } else {
          return this.$message.success("数据不完整");
          return false;
        }
      });
    },
    handleClose() {
      this.loginCount = 0;
      this.resetPwdDialog = false;
    },
    toRegister() {
      this.$router.push("/register");
    },
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          // 开启动画
          this.loading = true;
          this.userLogin();
          // 3秒没有相应则关闭动画
        } else {
        }
      });
    },
    userLogin() {
      let params = new URLSearchParams();
      params.append("cardNum", this.userForm.cardNum);
      params.append("password", this.userForm.password);
      // 开启动画
      setTimeout(() => {
        this.loading = false;
      }, 3000);
      this.$http
        .post("auth/login", params)
        .then(resp => {
          // 关闭动画
          this.loading = false;
          let { code, msg } = resp.data;
          let { userToken } = resp.data.data;
          if (code === 1) {
            sessionStorage.setItem("USER-TOKEN", userToken);
            this.$router.push("/welcome");
            return this.$message.success("登录成功,欢迎来到阿布校理！");
          } else {
            this.loginCount++;
            this.$notify({
              title: "警告！！！",
              message: msg,
              type: "warning",
              position: "top-left"
            });
          }
        })
        .catch(resp => {
          this.loading = false;
        });
    },
    thirdToLogin() {
      // 开启动画
      setTimeout(() => {
        this.loading = false;
      }, 3000);
      this.$http
        .get("/user/noAuthorize/render")
        .then(resp => {
          // 关闭动画
          this.loading = false;
          let { code, msg } = resp.data;
          let { redirectUrl } = resp.data.data;
          window.location.href = redirectUrl;
        })
        .catch(resp => {
          this.loading = false;
        });
    },
    cancalRestPwd() {
      this.loginCount = 0;
      this.resetPwdDialog = false;
    }
  },
  watch: {
    loginCount(newVal, oldVal) {
      console.log(oldVal, newVal);
      if (newVal == 3) {
        this.resetPwdDialog = true;
      }
    }
  }
};
</script >
 
<style scoped lang='less'>
.whole_black {
  top: 0;
  bottom: 0;
  position: fixed;
  overflow-y: scroll;
  overflow-x: hidden;
  width: 100%;
  height: 100%;
  background-image: url(../../assets/bg.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.box-card {
  border-radius: 15px;
  width: 340px;
  height: 360px;
  margin-top: 130px;
  margin-left: 780px;
  box-shadow: 5px 5px 5px;
}

.login-total {
  text-align: center;
}

.img-wechat {
  width: 30px;
  height: 30px;
  margin-left: 135px;
}
.userLogin {
  margin-left: 13px;
}
.imgLink {
  width: 30px;
  height: 30px;
}
.input-with-select {
  width: 350px;
}
.resetPwd {
  width: 100px;
}

.connect {
  width: 450px;
}
.checkButton {
  float: right;
}
</style>